﻿using NHibernate.Criterion;
using Online_Course.Core;
using Online_Course.Domain;
using Online_Course.Service;
using Online_Course.Web.Apps;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Online_Course.Web.Controllers
{
    public class SysRoleController : Controller
    {
        //
        // GET: /SysRole/
        #region 列表
        public ActionResult Index(int pageIndex = 1, string qryUserName = "")
        {
            //满足条件记录总数
            int count = 0;
            IList<Order> listOrder = new List<Order>() { new Order("ID", true) };
            IList<SysRole> list = Container.Instance.Resolve<ISysRoleService>().Query(new List<ICriterion>() { new LikeExpression("Name", "%" + qryUserName + "%") }, listOrder, pageIndex, PagerHelper.PageSize, out count);
            //转换为PageList集合
            PageList<SysRole> pageList = list.ToPageList<SysRole>(
                pageIndex
                , PagerHelper.PageSize
                , count);
            return View(pageList);//用pageList集合填充页面。
        }
        #endregion

        #region 新增
        public ActionResult Create()
        {
            SysRole Role = new SysRole();
            //获取所有菜单
            IList<SystemFunction> lst = Container.Instance.Resolve<ISystemFunctionService>().GetAll();
            IList<SelectListItem> lstRole = new List<SelectListItem>();
            //构建角色多选框的内容；
            foreach (var r in lst)
            {
                SelectListItem sli = new SelectListItem() { Text = r.Name, Value = r.ID.ToString(), Selected = false };
                lstRole.Add(sli);
            }
            ViewBag.lstRole = lstRole;
            //构建状态信息
            IList<SelectListItem> lstIsActive = new List<SelectListItem>() 
                { 
                     new SelectListItem(){Value="1",Text="激活",Selected=true},
                     new SelectListItem(){Value="2",Text="禁用",Selected=false}
                };
            ViewBag.lstIsActive = lstIsActive;
            return View(Role);

        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="user">用户实体</param>
        /// <param name="roleIDs">角色IDS</param>
        /// <param name="statusValue">用户状态</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(SysRole role, string roleIDs = "", string statusValue = "0", string studentId = "0", string teacherId = "0")
        {
            try
            {
                //拆分角色字符串；
                string[] arrIds = roleIDs.Split(',');
                IList<SystemFunction> roleFunction = new List<SystemFunction>();
                foreach (string n in arrIds)
                {
                    if (n != null && n != "")
                    {
                        //根据ID查找角色菜单
                        roleFunction.Add(Container.Instance.Resolve<ISystemFunctionService>().GetEntity(Int32.Parse(n)));
                    }
                }
                //构建实体
                role.SystemFunctionList = roleFunction;
                role.IsActive = Int32.Parse(statusValue);
                //保存到数据库中
                Container.Instance.Resolve<ISysRoleService>().Add(role);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region 修改
        public ActionResult Edit(int id)
        {
            //根据ID 查询要修改的实体
            SysRole entity = Container.Instance.Resolve<ISysRoleService>().GetEntity(id);
            //查询所有菜单信息；
            IList<SystemFunction> roleList = Container.Instance.Resolve<ISystemFunctionService>().GetAll();
            //构建菜单多选框，标记哪些菜单被选中
            IList<SelectListItem> sliFunction = new List<SelectListItem>();
            foreach (SystemFunction r in roleList)
            {
                bool isExist = false;
                //查找是否存在该用户的角色列表中；
                int count = entity.SystemFunctionList.Where(o => o.ID == r.ID).Count();
                //如果>0，则要被选中，否则不勾选；
                if (count > 0)
                { isExist = true; }
                SelectListItem sli = new SelectListItem() { Text = r.Name, Value = r.ID.ToString(), Selected = isExist };
                sliFunction.Add(sli);
            }
            ViewBag.sliFunction = sliFunction;



            //构建状态，并标记是否被选中；
            IList<SelectListItem> lstStatus = new List<SelectListItem>();
            SelectListItem itm = new SelectListItem() { Value = "1", Text = "激活", Selected = false };
            if (entity.IsActive.Equals(1))
            {
                itm.Selected = true;
            }
            lstStatus.Add(itm);
            itm = new SelectListItem() { Value = "0", Text = "禁用", Selected = false };
            if (entity.IsActive.Equals(0))
            {
                itm.Selected = true;
            }

            lstStatus.Add(itm);
            ViewBag.Status = lstStatus;
            return View(entity);
        }

        [HttpPost]
        public ActionResult Edit(int id, SysRole entity, string roleIDs = "", string statusValue = "0", string teacherId = "0", string studentId = "0")
        {

            //根据ID获取需要修改的用户；
            SysRole role = Container.Instance.Resolve<ISysRoleService>().GetEntity(id);
            try
            {
                string[] arrIds = roleIDs.Split(',');
                IList<SystemFunction> roleFunction = new List<SystemFunction>();
                foreach (string n in arrIds)
                {
                    if (n != null && n != "")
                    {
                        //查询当前ID的角色菜单，并添加到角色菜单列表中
                        roleFunction.Add(Container.Instance.Resolve<ISystemFunctionService>().GetEntity(Int32.Parse(n)));
                    }
                }
                //构建用户实体
                role.SystemFunctionList = roleFunction;
                //user.Password = AppHelper.EncodeMd5(user.Password);
                role.IsActive = Int32.Parse(statusValue);
                role.Name = entity.Name;

                //修改实体，保存
                Container.Instance.Resolve<ISysRoleService>().Update(role);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region 操作
        public ActionResult SwitchStatus(int id, string type)
        {
            SysRole role = Container.Instance.Resolve<ISysRoleService>().GetEntity(id);
            if (type.Equals("Active"))
            {
                role.IsActive = 1;
            }
            else if (type.Equals("Enabled"))
            {
                role.IsActive = 0;
            }
            Container.Instance.Resolve<ISysRoleService>().Update(role);
            return RedirectToAction("Index");//跳转到列表页面
        }
        public ActionResult Delete(int id)
        {
            SysRole Role = Container.Instance.Resolve<ISysRoleService>().GetEntity(id);
            Container.Instance.Resolve<ISysRoleService>().Delete(Role);
            return RedirectToAction("Index");
        }
        #endregion
	}
}